package com.sunbo509.www.gridview;

import android.graphics.Canvas;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import es.dmoral.toasty.Toasty;

public class MediaActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView path;
    private Button play,pause,replay;
    private SurfaceView sv;
    private MediaPlayer player=null;
    private int current;
    private SeekBar sb;
    private boolean isplaying;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_media);
        initView();
    }

   public void  initView(){
       path=(TextView)findViewById(R.id.path);
       play=(Button)findViewById(R.id.play);
       pause=(Button)findViewById(R.id.pause);
       replay=(Button)findViewById(R.id.replay);
       sv=(SurfaceView)findViewById(R.id.sv);
       sv.getHolder().addCallback(new SurfaceHolder.Callback() {
           @Override
           public void surfaceCreated(SurfaceHolder holder) {
               if (current > 0) {
                 play(current);
               }
           }
           @Override
           public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
           }

           @Override
           public void surfaceDestroyed(SurfaceHolder holder) {
          if(player!=null&&player.isPlaying()){
              current = player.getCurrentPosition();
              player.reset();
              }

           }
       });





         sb=(SeekBar)findViewById(R.id.sb);
         sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
             @Override
             public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

             }

             @Override
             public void onStartTrackingTouch(SeekBar seekBar) {

             }

             @Override
             public void onStopTrackingTouch(SeekBar seekBar) {
                 int position=seekBar.getProgress();
                    if(player!=null&&player.isPlaying()){
                        player.seekTo(position);
                    }
             }
         });

       play.setOnClickListener(this);
       pause.setOnClickListener(this);
       replay.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.play:
                play(0);
                break;
            case R.id.pause:
                pause();
                break;
            case R.id.replay:
                replay();
                break;
            default:
                break;
        }
    }

    private void replay() {
        if(player!=null&&player.isPlaying()){
            player.seekTo(0);
            play(0);
        }
    }

    private void pause() {
        if("继续".equals(pause.getText().toString().trim())){
            player.start();
            pause.setText("中止");
            return;
        }
        if(player!=null&&player.isPlaying()){
            player.pause();
            pause.setText("继续");
        }
    }

    private void play(final int value) {
        sv.setVisibility(View.VISIBLE);
        if("继续".equals(pause.getText().toString().trim())){
            player.start();
            return;
        }

//        String data = getSDPath() + "/" + "do.mp3";
        String data = getSDPath() + "/" + "do.mp4";
        String data1=getSDPath()+"/"+"do1.mp4";
        if(data!=null) {
            player = getMedia();
            if(player.isPlaying())
                return;
            player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                try {
                        player.setDataSource(data1);
                        player.prepareAsync();//异步
                        player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                            @Override
                            public void onPrepared(MediaPlayer mp) {
                                player.setDisplay(sv.getHolder());
                                int max = player.getDuration();
                                sb.setMax(max);
                                mp.start();
                                mp.seekTo(value);
                            }
                        });
                    } catch (IOException e) {
                    e.printStackTrace();
                }
            new Thread(){
                            public void run(){
                                isplaying=true;
                             while(isplaying){
                               if(player!=null&player.isPlaying()){
                                   int position=player.getCurrentPosition();
                                   sb.setProgress(position);
                                   try {
                                       Thread.sleep(500);
                                   } catch (InterruptedException e) {
                                       e.printStackTrace();
                                   }
                               }

                             }
                    }
                    }.start();

                    player.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                        @Override
                        public boolean onError(MediaPlayer mp, int what, int extra) {
                            isplaying=false;
                            return false;
                        }
                    });
                    player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {

                            mp.seekTo(0);
                            mp.start();
                        }
                    });
    }
    else
            Toasty.warning(MediaActivity.this, "音频不存在", Toast.LENGTH_SHORT).show();
    }
//获取SD目录
    public String getSDPath(){
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED);//判断sd卡是否存在
        if(sdCardExist)
        {
            sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        }
        return sdDir.toString();
    }

    //单例模式
    private static MediaPlayer media;
    public MediaPlayer getMedia(){
        if(media==null){
            media=new MediaPlayer();
        }
        return media;
    }


}
